﻿using Newtonsoft.Json;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Net.Http;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Model;
using Org.BouncyCastle.Asn1.X509;
using Model;
namespace OliveAirLeakTest.MES
{
    public class MESHelper
    {
        private static readonly HttpClient _httpClient;
        private static Stopwatch sw;

        private string EquipmentCode { get; set; }

        private int UserId { get; set; } = 10086;

        private string MaterialCode { get; set; }

        private bool IsOnline { get; set; } = true;
        private bool isTask;

        private bool isLoad;
        private bool isReport;
        private bool isUpdata;

        public SysSettings systemSettings;

        static MESHelper()
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
            sw = new Stopwatch();
        }

        public MESHelper()
        {
           
        }

        public MESHelper(SysSettings setting)
        {
            systemSettings = setting;
        }

        /// <summary>
        /// info日志回调接口
        /// </summary>
        public static event Action<string> LogInfoWrite;

        /// <summary>
        /// Error日志回调接口
        /// </summary>
        public static event Action<string> LogErrorWrite;

        public void SET(SysSettings setting)
        {
            systemSettings = setting;

            //UrlGet = setting.UrlGet;
            //UrlLoad = setting.UrlLoad;
            //UrlReport = setting.UrlReport;
            //UrlUpload = setting.UrlMESUpload;
            //EquipmentCode = setting.EquipmentCode;
            //UserId = setting.UserId;
            //MaterialCode = product.MaterialCode;
            //IsGet = product.IsTask;
            //IsLoad = product.IsMESLoad;
            //IsReport = product.IsMESReport;
            //IsUpload = product.IsDataUpload;
        }

        // Fix for CS0120: Make GetStringAsync non-static to access instance properties
        public async Task<List<TaskDetail>> GetTaskAsync()
        {
            // Fix for CS0103: Pass the required parameters explicitly
            var str = $"{systemSettings.UrlGet}?equipmentCode={EquipmentCode}&userId={UserId}&productCode={MaterialCode}";
            LogInfoWrite?.Invoke($"工单获取发送报文 {str}");
            try
            {
                sw.Restart();
                HttpResponseMessage response = await _httpClient.GetAsync(str);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                sw.Stop();
                LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms,工单获取返回报文 {responseBody}");

                var result = JsonConvert.DeserializeObject<RecvTaskDetail>(responseBody);
                if (result != null && result.Data != null && result.Data.Count > 0)
                {
                    return result.Data;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogErrorWrite?.Invoke($"工单获取异常 {ex.Message}");
                return null;
            }
        }

        //public async Task<bool> LoadMaterialAsync(LoadMaterialMessage loadMaterialMessage)
        //{
        //    var str = JsonConvert.SerializeObject(loadMaterialMessage);
        //    LogInfoWrite?.Invoke($"过站发送报文{str}");
        //    try
        //    {
        //        sw.Restart();
        //        string jsonstr = await SendHttpPostAsync(systemSettings.UrlLoad, str);
        //        sw.Stop();
        //        LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms，过站返回报文{jsonstr}");
        //        var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(jsonstr);
        //        if (recvMaterialMessage?.Data?.Count > 0)
        //        {
        //            foreach (var item in recvMaterialMessage.Data)
        //            {
        //                if (item.ProductSerialNumber == loadMaterialMessage.ProductSerialNumberList[0])
        //                {
        //                    LogInfoWrite?.Invoke($"过站解析成功{item.ProductSerialNumber}校验值为{item.Success.ToString()}");
        //                    return item.Success;

        //                }
        //            }
        //            LogInfoWrite?.Invoke("过站返回报文未包含发送的二维码");
        //            return false;
        //        }
        //        LogInfoWrite?.Invoke("过站码文为空");
        //        return false;
        //    }
        //    catch(Exception ex)
        //    {
        //        LogErrorWrite?.Invoke($"过站发生错误{ex.Message}");
        //        return false;
        //    }

        //}
        public async Task<bool> LoadMaterialAsync(string ProductSerialNumber, string taskId)
        {
            if (!IsOnline || !isLoad)
            {
                LogInfoWrite?.Invoke("MES过站功能未启用或MES未在线");
                return true;
            }
            if (isTask && string.IsNullOrEmpty(taskId))
            {
                LogInfoWrite?.Invoke("工单号不能为空");
                return false;
            }
            LoadMaterialMessage loadMaterialMessage = new LoadMaterialMessage();
            {
                loadMaterialMessage.EquipmentCode = EquipmentCode;
                loadMaterialMessage.ProductSerialNumberList = new List<string>();
                loadMaterialMessage.ProductSerialNumberList.Add(ProductSerialNumber);
                loadMaterialMessage.UserId = UserId;
                loadMaterialMessage.TaskId = taskId;
            }
            var str = JsonConvert.SerializeObject(loadMaterialMessage);
            LogInfoWrite?.Invoke($"过站发送报文{str}");
            try
            {
                sw.Restart();
                string jsonstr = await SendHttpPostAsync(systemSettings.UrlLoad, str);
                sw.Stop();
                LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms，过站返回报文{jsonstr}");
                var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(jsonstr);
                if (recvMaterialMessage?.Data?.Count > 0)
                {
                    foreach (var item in recvMaterialMessage.Data)
                    {
                        if (item.ProductSerialNumber == loadMaterialMessage.ProductSerialNumberList[0])
                        {
                            LogInfoWrite?.Invoke($"过站解析成功{item.ProductSerialNumber}校验值为{item.Success.ToString()}");
                            return item.Success;
                        }
                    }
                    LogInfoWrite?.Invoke("过站返回报文未包含发送的二维码");
                    return false;
                }
                LogInfoWrite?.Invoke("过站码文为空");
                return false;
            }
            catch (Exception ex)
            {
                LogErrorWrite?.Invoke($"过站发生错误{ex.Message}");
                return false;
            }
        }

        //public async Task<bool> ReportWorkAsync(ReportWorkMessage reportWorkMessage)
        //{
        //    try
        //    {
        //        var str = JsonConvert.SerializeObject(reportWorkMessage);
        //        LogInfoWrite?.Invoke($"报工发送报文：{str}");

        //        sw.Restart();

        //        var result = await SendHttpPostAsync(systemSettings.UrlReport, str);
        //        sw.Stop();
        //        LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms，报工返回报文：{result}");
        //        var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
        //        if (recvMaterialMessage?.Data?.Count > 0)
        //        {
        //            foreach (var item in recvMaterialMessage.Data)
        //            {
        //                if (item.ProductSerialNumber == reportWorkMessage.ProductSerialNumberInfoList[0].ProductSerialNumber)
        //                {
        //                    LogInfoWrite?.Invoke($"报工解析成功{item.ProductSerialNumber}校验值为{item.Success.ToString()}");
        //                    return item.Success;

        //                }
        //            }
        //            LogInfoWrite?.Invoke("报工返回报文未包含发送的二维码");
        //            return false;
        //        }
        //        LogInfoWrite?.Invoke("报工码文为空");
        //        return false;
        //    }
        //    catch(Exception ex)
        //    {
        //        LogErrorWrite?.Invoke($"报工发生错误{ex.Message}");
        //        return false;
        //    }
        //}
        public async Task<bool> ReportMultiWorkAsync(List<string> ProductSerialNumList,string taskId,string Resultstr,string ext)
        {
            if (!IsOnline || !isReport)
            {
                LogInfoWrite?.Invoke("MES报工功能未启用或MES未在线");
                return true;
            }
            if (isTask && string.IsNullOrEmpty(taskId))
            {
                LogInfoWrite?.Invoke("工单号不能为空");
                return false;
            }
            ReportWorkMessage reportWorkMessage = new ReportWorkMessage();
            reportWorkMessage.UserId = UserId;
            reportWorkMessage.EquipmentCode = EquipmentCode;
            reportWorkMessage.TaskId = taskId;
            
            foreach(var productSerialNumber in ProductSerialNumList)
            {
                ProductSerialNumberInfoList productSerialNumberInfo = new ProductSerialNumberInfoList();
                productSerialNumberInfo.ProductSerialNumber = productSerialNumber;
                productSerialNumberInfo.Result = Resultstr;
                productSerialNumberInfo.Ext = ext;
                reportWorkMessage.ProductSerialNumberInfoList.Add(productSerialNumberInfo);
            }
            try
            {
                var str = JsonConvert.SerializeObject(reportWorkMessage);
                LogInfoWrite?.Invoke($"报工发送报文：{str}");

                sw.Restart();

                var result = await SendHttpPostAsync(systemSettings.UrlReport, str);
                sw.Stop();
                LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms，报工返回报文：{result}");
                var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
                if (recvMaterialMessage?.Data?.Count > 0)
                {
                    foreach (var item in recvMaterialMessage.Data)
                    {
                        if (item.ProductSerialNumber == reportWorkMessage.ProductSerialNumberInfoList[0].ProductSerialNumber)
                        {
                            LogInfoWrite?.Invoke($"报工解析成功{item.ProductSerialNumber}校验值为{item.Success.ToString()}");
                            return item.Success;
                        }
                    }
                    LogInfoWrite?.Invoke("报工返回报文未包含发送的二维码");
                    return false;
                }
                LogInfoWrite?.Invoke("报工码文为空");
                return false;
            }
            catch (Exception ex)
            {
                LogErrorWrite?.Invoke($"报工发生错误{ex.Message}");
                return false;
            }


        }
        public async Task<bool> ReportWorkAsync(string ProductSerialNumber, string taskId, string Resultstr, string ext)
        {
            if (!IsOnline || !isReport)
            {
                LogInfoWrite?.Invoke("MES报工功能未启用或MES未在线");
                return true;
            }
            if (isTask && string.IsNullOrEmpty(taskId))
            {
                LogInfoWrite?.Invoke("工单号不能为空");
                return false;
            }

            ReportWorkMessage reportWorkMessage = new ReportWorkMessage();
            reportWorkMessage.UserId = UserId;
            reportWorkMessage.EquipmentCode = EquipmentCode;
            reportWorkMessage.TaskId = taskId;
            reportWorkMessage.ProductSerialNumberInfoList = new List<ProductSerialNumberInfoList>();
            ProductSerialNumberInfoList productSerialNumberInfo = new ProductSerialNumberInfoList();
            productSerialNumberInfo.ProductSerialNumber = ProductSerialNumber;
            productSerialNumberInfo.Result = Resultstr;
            productSerialNumberInfo.Ext = ext;
            reportWorkMessage.ProductSerialNumberInfoList.Add(productSerialNumberInfo);
            try
            {
                var str = JsonConvert.SerializeObject(reportWorkMessage);
                LogInfoWrite?.Invoke($"报工发送报文：{str}");

                sw.Restart();

                var result = await SendHttpPostAsync(systemSettings.UrlReport, str);
                sw.Stop();
                LogInfoWrite?.Invoke($"用时{sw.ElapsedMilliseconds}ms，报工返回报文：{result}");
                var recvMaterialMessage = JsonConvert.DeserializeObject<RecvMaterialMessage>(result);
                if (recvMaterialMessage?.Data?.Count > 0)
                {
                    foreach (var item in recvMaterialMessage.Data)
                    {
                        if (item.ProductSerialNumber == reportWorkMessage.ProductSerialNumberInfoList[0].ProductSerialNumber)
                        {
                            LogInfoWrite?.Invoke($"报工解析成功{item.ProductSerialNumber}校验值为{item.Success.ToString()}");
                            return item.Success;
                        }
                    }
                    LogInfoWrite?.Invoke("报工返回报文未包含发送的二维码");
                    return false;
                }
                LogInfoWrite?.Invoke("报工码文为空");
                return false;
            }
            catch (Exception ex)
            {
                LogErrorWrite?.Invoke($"报工发生错误{ex.Message}");
                return false;
            }
        }

        private async Task<string> SendHttpPostAsync(string url, string jsonBody)
        {
            try
            {
                var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
               // response.EnsureSuccessStatusCode();

                string responsebody = await response.Content.ReadAsStringAsync();
                return responsebody;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public async Task<bool> MESUpdata(Recode record)
        {
            if (!IsOnline || !isUpdata)
            {
                LogInfoWrite?.Invoke("MES数据上传功能未启用或MES未在线");
                return false;
            }
            //if (isTask && string.IsNullOrEmpty(record.ProdTaskId))
            //{
            //    LogErrorWrite?.Invoke($"数据上传任务单号不能为空");
            //    return false;
            //}
            try
            {
                ///
                var json = JsonConvert.SerializeObject(record, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" });
                LogInfoWrite?.Invoke($"数据上传报文：{json}");
                sw.Restart();
                var response = await SendHttpPostAsync(systemSettings.UrlUpdata, json);
                sw.Stop();

                LogInfoWrite?.Invoke($"耗时{sw.ElapsedMilliseconds}毫秒,数据上传返回报文{response}");
                var recvUpdata = JsonConvert.DeserializeObject<RecvUpdata>(response);
                if (recvUpdata == null)
                {
                    LogErrorWrite?.Invoke($"数据上传失败：{response}");
                    return false;
                }
                else if (recvUpdata.Code == 200)
                {
                    LogInfoWrite?.Invoke($"数据上传成功。");
                    return true;
                }
                else
                {
                    LogErrorWrite?.Invoke($"数据上传失败：{recvUpdata.Msg}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogErrorWrite?.Invoke($"数据上传出错：{ex.Message}");
                return false;
            }
        }
    }
}